import express from 'express'
import cors from 'cors'
import fs from 'fs'
import path from 'path'
import url from 'url'

const app = express()
app.use(cors())

const helloCode = `
window.__string_app_mount__ = function(api){
  const el = api.mount
  el.innerHTML = '<div id="sub-hello">Hello 子应用（来自注册中心字符串）</div>'
}
`

const formCode = `
window.__string_app_mount__ = function(api){
  const el = api.mount
  el.innerHTML = '<div id="sub-form" style="padding:12px;">\n  <h3>表单子应用</h3>\n  <form>\n    <label>姓名：<input id="name" /></label><br/>\n    <label>手机号：<input id="phone" /></label><br/>\n    <button type="button" id="ok">提交</button>\n  </form>\n</div>'
  document.getElementById('ok').addEventListener('click', ()=>{
    alert('提交成功：' + document.getElementById('name').value)
  })
}
`

const adminCode = `
window.__string_app_mount__ = function(api){
  const el = api.mount
  el.innerHTML = '<div id="sub-admin" style="padding:12px;">\n  <h3>管理后台子应用（字符串版本）</h3>\n  <p>这是管理后台的字符串版本，用于兜底。</p>\n</div>'
}
`

app.get('/app-string', (req, res) => {
  const appKey = req.query.app || 'hello'
  
  // 优先尝试读取 subapp-c 构建产物
  try {
    const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
    // 修复路径：从 registry-c 目录向上两级到根目录，然后进入 subapp-c/dist
    const root = path.resolve(__dirname, '../subapp-c/dist', appKey)
    console.log(appKey,'server.js appkey')
    const file = path.join(root, 'index.iife.js')
    
    console.log('尝试读取文件:', file)
    console.log('尝试读取文件:', fs.existsSync(file))
    if (fs.existsSync(file)) {
      console.log('找到构建产物，返回文件内容')
      const code = fs.readFileSync(file, 'utf-8')
      return res.type('text/javascript').send(code)
    } else {
      console.log('构建产物不存在，使用兜底代码')
    }
  } catch (e) {
    console.error('读取构建产物时出错:', e.message)
  }
  
  // 兜底字符串代码
  if (appKey === 'form') return res.type('text/javascript').send(formCode)
  if (appKey === 'admin') return res.type('text/javascript').send(adminCode)
  return res.type('text/javascript').send(helloCode)
})

// 新增：提供 CSS 样式文件
app.get('/app-style', (req, res) => {
  const appKey = req.query.app || 'hello'
  console.log(req,res,'cssssssssssssssssss')
  try {
    const __dirname = path.dirname(url.fileURLToPath(import.meta.url))
    const root = path.resolve(__dirname, '../subapp-c/dist', appKey)
    const cssFile = path.join(root, 'style.css')
    
    console.log('尝试读取样式文件:', cssFile)
    
    if (fs.existsSync(cssFile)) {
      console.log('找到样式文件，返回 CSS 内容')
      const css = fs.readFileSync(cssFile, 'utf-8')
      return res.type('text/css').send(css)
    } else {
      console.log('样式文件不存在')
      return res.status(404).send('Style file not found')
    }
  } catch (e) {
    console.error('读取样式文件时出错:', e.message)
    return res.status(500).send('Error reading style file')
  }
})

const port = process.env.PORT || 7070
app.listen(port, () => console.log('Registry C running at http://localhost:' + port))


